package post

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/forum/rpc/forumclient"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPostFavoriteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPostFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostFavoriteLogic {
	return &GetPostFavoriteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPostFavoriteLogic) GetPostFavorite(
	req *types.GetForumPostFavoriteReq,
	headers *[]*types.Header,
) (resp *types.TmpPostListResp, err error) { // Todo: 待实现
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)
	favPreload := "forumUserCollect:Id,ObjectId"
	// 构造查询条件
	var favFilters []string
	favFilters = append(favFilters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))
	favFilters = append(favFilters, "PlatformId,equalTo:"+strconv.FormatInt(int64(globalkey.ThirdPartyPlatformWechatMini), 10))
	favFilters = append(favFilters, "ObjectType,equalTo:"+strconv.FormatInt(int64(globalkey.AttachmentLogTypePost), 10))
	favFilters = append(favFilters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	var platformId = globalkey.ThirdPartyPlatformWechatMini

	ret, err := l.svcCtx.ForumRpc.GetUserCollectList(l.ctx, &forumclient.BaseListReq{
		Offset:     uint32((page - 1) * pageSize),
		Limit:      uint32(pageSize),
		Preload:    pointy.GetPointer(favPreload),
		Filter:     pointy.GetPointer(strings.Join(favFilters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(platformId),
	})
	if err != nil {
		return nil, err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if ret.HasNextPage != nil && *ret.HasNextPage > 0 {
		hasNextPage = true
	}
	if ret.HasPreviousPage != nil && *ret.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp = &types.TmpPostListResp{
		BaseListInfo: types.BaseListInfo{
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	if len(ret.List) > 0 {
		var pids []string
		for _, v := range ret.List {
			if v.ObjectId != nil && *v.ObjectId > 0 {
				pids = append(pids, strconv.FormatInt(int64(*v.ObjectId), 10))
			}
		}
		//preload := "product:Id,Title,Slug"
		//eagerLoad := "product:productMeta,productMedia,productRelationship"
		//preload += ";productMeta:mediaUrl,retailPriceMin,hotSell"
		//preload += ";productMedia:Uid,Url,altText,metaData"
		//preload += ";productRelationship:PerfumeId,PerfumeName,PerfumeSlug,BrandId,BrandName,BrandSlug"
		preload := "blogPost:Id,AuthorId,Title,Excerpt,Date,Modified,AuthorIp,Anonymous"
		eagerLoad := "blogPost:blogMedia"
		preload += ";blogMedia:Uid,Url,Thumbnail,altText"

		var filters []string
		filters = append(filters, "Id,in:"+strings.Join(pids, ","))
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))

		res, err := l.svcCtx.BlogRpc.PostList(l.ctx, &blogclient.PostListReq{
			Preload:   preload,
			EagerLoad: eagerLoad,
			Filter:    strings.Join(filters, ";"),
		})
		if err != nil {
			return nil, err
		}

		resp = &types.TmpPostListResp{
			BaseListInfo: types.BaseListInfo{
				Total:    uint64(len(res.Data)),
				Current:  page,
				PageSize: pageSize,
			},
		}

		if len(res.Data) > 0 {
			//获取图片信息
			for _, v := range res.Data {
				var photos []*types.MediaInfo
				if len(v.Media) > 0 {
					for _, m := range v.Media {
						var url string
						if len(m.Url) > 0 {
							url = m.Url
						}
						if len(url) == 0 && len(m.Uri) > 0 {
							url = m.Uri
						}
						photos = append(photos, &types.MediaInfo{
							Uid:     pointy.GetPointer(uint64(m.Uid)),
							Id:      pointy.GetPointer(strconv.FormatUint(uint64(m.Id), 10)),
							Url:     pointy.GetPointer(url),
							AltText: pointy.GetPointer(m.AltText),
							Details: pointy.GetPointer(m.Meta),
						})
					}
				}
				var authorId *uint64
				var nickName, avatar *string
				if v.AuthorId > 0 {
					auth, err := l.svcCtx.UserRpc.GetUserAuthByUserId(l.ctx, &userclient.GetUserAuthByUserIdReq{
						UserId:     pointy.GetPointer(uint64(v.AuthorId)),
						PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
					})
					if err != nil {
						return nil, err
					}
					authorId = auth.UserId
					nickName = auth.Nickname
					avatar = auth.Avatar
				}

				//获取Postinfo，包括作者以及作品title
				resp.List = append(resp.List, &types.TmpBlogPostInfo{
					BaseIDInfo: types.BaseIDInfo{
						Id:        pointy.GetPointer(uint64(v.Id)),
						CreatedAt: pointy.GetPointer(v.Date),
						UpdatedAt: pointy.GetPointer(v.Date),
						DeletedAt: pointy.GetPointer(v.Date),
					},
					Author: &types.AuthorInfo{
						Id:     authorId,
						Name:   nickName,
						Avatar: avatar,
					},
					Title: pointy.GetPointer(v.Title),
					Media: photos,
				})
			}
		}

	}

	//todo:待修改
	*headers = []*types.Header{
		{
			Key:   "x-class",
			Value: "com.djx.appview.GoodsFavPage",
		},
	}

	return resp, nil
}
